package at.fhj.itm09.snake.activities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import at.fhj.itm09.snake.R;

/**
 * @author Susanne Brandstätter - Susanne.Brandstaetter.ITM09@fh-joanneum.at
 * @author Katharina Biela - Katharina.Biela.ITM09@fh-joanneum.at
 *
 * This activity shows the layout to load a picture from the Web.
 * After inserting an url to the edittext field you can click on the button and 
 * the picture getting loaded from the web. 
 * When the download is finished, the loaded image is shown.
 * 
 */

public class LoadPictureActivity extends Activity implements OnClickListener{
	private EditText inputUrl;
	private TextView loadMessage;
	private String extStorageDirectory;
	private Bitmap bm;


	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.load_image_from_url);
		inputUrl = ((EditText)findViewById(R.id.imageUrl));
		inputUrl.setTextSize(11);
		
		loadMessage = (TextView) findViewById(R.id.loadMessage);
		
		Button getImageButton = (Button)findViewById(R.id.btn_loadPhoto);
		getImageButton.setOnClickListener(this);

		extStorageDirectory = "/sdcard/";
	}	


	/**
	 * With clicking on the button, the picture gets downloaded from the web.
	 * If the download is finished, the picture gets saved. 
	 */
	public void onClick(View view) {
		Context context = view.getContext();
		ImageView imgView = new ImageView(context);
		imgView = (ImageView)findViewById(R.id.image1);

	    BitmapFactory.Options bmOptions;
	    bmOptions = new BitmapFactory.Options();
	    bmOptions.inSampleSize = 1;
	    bm = LoadImage(inputUrl.getText().toString(), bmOptions);
	    imgView.setImageBitmap(bm);
	    loadMessage.setText("Gespeichertes Foto:");
	    
	    savePicture(bm);
	}
	
	/**
	 * This method will be called by clicking on the button. 
	 * It will save the downloaded picture in PNG format. 
	 * 
	 * @param bm
	 */
	public void savePicture(Bitmap bm){
		OutputStream outStream = null;
	    File file = new File(extStorageDirectory, "myLoadedSnakeimage.PNG");
	    try {
		    outStream = new FileOutputStream(file);

		    bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
		    outStream.flush();
		    outStream.close();
		   
		    Toast.makeText(LoadPictureActivity.this, "Foto gespeichert", Toast.LENGTH_LONG).show();
		    
	    } catch (FileNotFoundException e) {
		    e.printStackTrace();
		    Log.e("Load", "file not found " + e);
		    Toast.makeText(LoadPictureActivity.this, e.toString(), Toast.LENGTH_LONG).show();
	    } catch (IOException e) {
		    e.printStackTrace();
		    Log.e("Load", "io " + e);
		    Toast.makeText(LoadPictureActivity.this, e.toString(), Toast.LENGTH_LONG).show();
	    }
	}
	
	/**
	 * This method is called by clicking on the button.
	 * 
	 * It's business is to call the method OpenHttpConnection and to decode the
	 * returned inputstream to an bitmap. 
	 * 
	 * When the image is fully loaded and decoded, it will return the bitmap. 
	 *  
	 * @param URL
	 * @param options
	 * @return
	 */
	private Bitmap LoadImage(String URL, BitmapFactory.Options options)
	{      
		Bitmap bitmap = null;
		InputStream in = null;      
		try {
			in = OpenHttpConnection(URL);
			bitmap = BitmapFactory.decodeStream(in, null, options);
			in.close();
		} catch (IOException e1) {
			Toast t = Toast.makeText(this, "Verbindungsaufbau ist fehlgeschlagen.", Toast.LENGTH_LONG);
			t.show();
			Log.e("Load", "Loading not successful");
		}
		return bitmap;              
	}
	
	/**
	 * It's business is to set up a http connection to can load the picture from
	 * the web. 
	 * 
	 * If the connection is successful, it will save the object in an inputstream.
	 * Afterwards it returns the inputstream.
	 * 
	 * @param strURL
	 * @return
	 * @throws IOException
	 */
	private InputStream OpenHttpConnection(String strURL) throws IOException{
		InputStream inputStream = null;
		URL url = new URL(strURL);
		URLConnection conn = url.openConnection();

		try{
			HttpURLConnection httpConn = (HttpURLConnection)conn;
			httpConn.setRequestMethod("GET");
			httpConn.connect();
		
			if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpConn.getInputStream();
			}
		}
		catch (Exception ex)
		{
			Log.e("Load", "Problem with HTTP Connection");
		}
		return inputStream;
	}
}